package com.hq.fjgl.actions;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.eredlab.g4.arm.util.ArmConstants;
import org.eredlab.g4.arm.util.idgenerator.IDHelper;
import org.eredlab.g4.ccl.datastructure.Dto;
import org.eredlab.g4.ccl.datastructure.impl.BaseDto;
import org.eredlab.g4.ccl.json.JsonHelper;
import org.eredlab.g4.ccl.util.G4Constants;
import org.eredlab.g4.ccl.util.G4Utils;
import org.eredlab.g4.rif.web.BaseAction;
import org.eredlab.g4.rif.web.CommonActionForm;

import com.hq.fjgl.service.UploadService;

public class AttachmentAction extends BaseAction{
	//获得附件管理服务类
	private UploadService uploadService = (UploadService) getService("fjglService");
	
	//项目的显示页面
	public ActionForward fjglInit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return mapping.findForward("fjglView");
	}
	
	/**
	 * 查询项目
	 * 
	 */
	public ActionForward querySfxm(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：进入到项目上报查询逻辑。。。。。。");
		CommonActionForm fForm = (CommonActionForm) form;
		Dto dto = fForm.getParamAsDto(request);
		List list = g4Reader.queryForPage("fjglDemo.queryCatalogsForPrint", dto);
		String jsonString = JsonHelper.encodeList2PageJson(list,(Integer)this.g4Reader.queryForObject("fjglDemo.queryCatalogsForPrintCount", dto), G4Constants.FORMAT_Date);
		super.write(jsonString, response);
		return mapping.findForward(null);
	}
	//查看附件信息页面
	public ActionForward fjglLook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		CommonActionForm fForm = (CommonActionForm) form;
		Dto dto = fForm.getParamAsDto(request);
		Dto exist=(Dto)this.g4Reader.queryForObject("fjglDemo.existPrj_sn",dto.getAsString("prj_sn"));
		if(exist==null||exist.getAsString("prj_sn")==null)
		{
			request.setAttribute("tip", "提示：对不起，此项目被他人已经删除，已经为你刷新了数据...");
			return mapping.findForward("fjglView");
		}
		else
		{
			//由于这里的所有操作只针对一个项目，因此可以当前的项目编号存放在会话中进行长会话操作！
			this.setSessionAttribute(request, "prj_sn",dto.getAsString("prj_sn"));
			System.out.println("提示：正在转换页面。。。。。。项目编号为："+dto.getAsString("prj_sn"));
			//得到根节点菜单的名字！通过菜单的编号，这个编号是唯一的！
			Dto pdto = (Dto)g4Reader.queryForObject("fjglDemo.queryAdminName", "0101");
			//将根节点名字保存起来！
			request.setAttribute("rootMenuName", pdto.getAsString("menuname"));
			request.setAttribute("prj_no",dto.getAsString("prj_no"));
			return mapping.findForward("fjView");
		}
	}
	//加载根节点下的所有子节点！
	public ActionForward queryMenuItems(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("正在加载附件类型下的所有子节点。。。。。。。。。。。。父节点编号是："+request.getParameter("node"));
		//的到传来的父节点编号，至今我还不知道这个参数是从那里来的
		String parentId=request.getParameter("node");
		Dto queryChild=new BaseDto();
		queryChild.put("parentid",parentId);
		List list=this.g4Reader.queryForList("fjglDemo.queryChildByAdmin",queryChild);
		Dto menuDto = new BaseDto();
		for (int i = 0; i < list.size(); i++) 
		{
			menuDto = (BaseDto) list.get(i);
			if (menuDto.getAsString("leaf").equals(ArmConstants.LEAF_Y))
				menuDto.put("leaf", new Boolean(true));
			else
				menuDto.put("leaf", new Boolean(false));
			if(menuDto.getAsString("id").length()==4)
			{
				menuDto.put("expanded",new Boolean(true));
			}
		}
		//将集合解析成json类型!
		write(JsonHelper.encodeObject2Json(list), response);
		return null;
	}
	

	//查看当前项目中的所有附件信息！
	public ActionForward queryFj(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		//一旦进入了操作附件的界面那么在session作用域中一定会存在一个名为prj_sn的属性，这个属性在跳转到当前项目附件管理模块时添加进去的，是个长会话！
		dto.put("prj_sn",this.getSessionAttribute(request, "prj_sn"));
		//默认情况加载当前项目编号下的所有附件信息！（仅仅是第一次进入时才是这样），但下次激发这个方法时可能就包含文件名啊，附件类型编号啊，等这些查询信息！
		List list=this.g4Reader.queryForPage("fjglDemo.queryFj",dto);
		//定义一个字符串变量用于接收附件的路径！
		String path="";
		for(int i=0;i<list.size();i++)
		{
			//由于要将数据转换成json类型，因此对于时间属性我们要进行处理，将其变长字符串类型，这样才能显示！
			((Dto)list.get(i)).put("attc_update", ((Dto)list.get(i)).getAsString("attc_update"));
			path=((Dto)list.get(i)).getAsString("attc_path");
			System.out.println("当前被修改的路径是："+path);
			//由于在前台要看的是文件名而不是路径因此要处理一下，截取文件名！
			((Dto)list.get(i)).put("filename",path.substring(path.lastIndexOf('\\')+1,path.lastIndexOf('.')));
			String filename1=path.substring(path.lastIndexOf('\\')+1,path.length());
			System.out.println("filename1："+filename1);
		}
		System.out.println("传递过来的参数有："+dto.toString());
		System.out.println("当前你要项目的id是："+this.getSessionAttribute(request, "prj_sn"));
		this.write(JsonHelper.encodeList2PageJson(list,(Integer)this.g4Reader.queryForObject("fjglDemo.queryFjCount",dto),null), response);
		return null;
	}
	//创建添加附件的方法
	public synchronized ActionForward saveFj(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在添加附件信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto inDto = aForm.getParamAsDto(request);
		//用系统的辅助工具类参数一个编号！
		String fjid=IDHelper.getCodeID();
		//将当前的会话项目id添加到参数中去！
		inDto.put("prj_sn",this.getSessionAttribute(request,"prj_sn"));
		inDto.put("attc_sn", fjid);
		inDto.put("LAND_SN",this.getSessionAttribute(request, "prj_sn"));
		inDto.put("attc_update",new Date());
		inDto=this.uploadFile(aForm, inDto);
		uploadService.addFj(inDto);
		setOkTipMsg("文件信息添加成功", response);
		return mapping.findForward(null);
	}
	
	//查看当前项目中的所有附件信息！
	public synchronized ActionForward updatePath(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在修改附件信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto inDto = aForm.getParamAsDto(request);
		inDto.put("prj_sn",this.getSessionAttribute(request,"prj_sn"));
		inDto.put("LAND_SN",this.getSessionAttribute(request, "prj_sn"));
		//强制覆盖标识！
		inDto.put("biaozhi","false");
		inDto=this.uploadFile(aForm, inDto);
		inDto.put("attc_update",new Date());
		this.uploadService.updatePath(inDto);
		this.setOkTipMsg("修改成功！", response);
		return null;
	}
	
	//只要为了添加附件路径键值对！
	private Dto uploadFile(CommonActionForm form,Dto beforedto)
	{
		FormFile file1=form.getFile1();
		String path=this.saveFile(file1, beforedto,beforedto.getAsBoolean("biaozhi"));
		System.out.println("===========================================================是否覆盖呢？"+beforedto.getAsBoolean("biaozhi"));
		System.out.println("---------------------------"+path);
		//填充保存路径！
		beforedto.put("attc_path",path);
		//将处理之后的dto返回！
		return beforedto;
	}
	
	private String  saveFile(FormFile myFile,Dto inDto,boolean isCoverd)
	{
		try 
		{
			String savePath = getServlet().getServletContext().getRealPath("/") + "file\\";
			File file = new File(savePath);
			if (!file.exists()) {
				file.mkdir();
			}
			savePath=savePath+inDto.getAsString("LAND_SN")+"\\";
			File file1 = new File(savePath);
			if (!file1.exists()) {
				file1.mkdir();
			}
			String fileName = myFile.getFileName();
			File fileToCreate = new File(savePath+fileName);
			//判断是否覆盖，如果覆盖就覆盖！
			if(isCoverd)
			{
				savePath=savePath+fileName;
			}
			else
			{
				//不覆盖也要分2中情况考虑，一种是不覆盖但也不存在，另一种是不覆盖但文件已经存在！如果不加判断就会一直创建新的别名文件，无论是否有！
				if(fileToCreate.exists())
				{
					savePath=savePath+fileName.replace(".",G4Utils.getCurrentTime("yyyy-MM-dd-hh-mm-ss")+".");
					fileToCreate=new File(savePath);
				}
				else
				{
					savePath=savePath+fileName;
				}
			}
			//如果文件已经存在了就覆盖原来的文件！
			if(savePath.length()>=200)
			{
					return null;
			}
			else
			{
					FileOutputStream os = new FileOutputStream(fileToCreate);
					os.write(myFile.getFileData());
					os.flush();
					os.close();
					return savePath.trim();
			}
		} 
		catch (Exception e) 
		{
			System.out.println(e.toString());
			return null;
		}
	}
	
	//创建删除附件的方法
	public ActionForward deleteFj(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在添加附件信息。。。。。。。");
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		String[] strChecked = dto.getAsString("strChecked").split(",");
		Dto delete=new BaseDto();
		//由于所有的删除都是针对同一个项目因此下面这个参数可以在循环外设置
		delete.put("prj_sn",this.getSessionAttribute(request, "prj_sn"));
		//循环覆盖，虚幻删除！
		for (int i = 0; i < strChecked.length; i++) 
		{
			delete.put("attc_sn",strChecked[i]);
			this.uploadService.deleteFj(delete);
		}
		setOkTipMsg("附件删除成功", response);
		return mapping.findForward(null);
	}
	//用于判断文件是否存在，就在在保存附件信息时判断，用于提示用户！
	public ActionForward fileIsExist(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("提示：正在判断当前文件是否存在。。。。。");
		CommonActionForm aForm=(CommonActionForm)form;
		Dto dto=aForm.getParamAsDto(request);
		String filePath = getServlet().getServletContext().getRealPath("/") + "file\\"+this.getSessionAttribute(request, "prj_sn")+dto.getAsString("path").substring(dto.getAsString("path").lastIndexOf('\\'));
		System.out.println("传递过来的文件名是："+filePath);
		try
		{
			File file=new File(filePath);
			//设置一个标志文件是否存在的标志！
			if(file.exists())
			{
				System.out.println("文件存在！");
				this.setOkTipMsg("exist", response);
			}
			else
			{
				System.out.println("文件不存在！");
				this.setOkTipMsg("noexist", response);
			}
		} 
		catch (Exception e)
		{
			System.out.println("文件不存在！");
			this.setOkTipMsg("noexist", response);
		}
		return null;
	}
	
	public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		CommonActionForm aForm = (CommonActionForm) form;
		Dto dto = aForm.getParamAsDto(request);
		String attc_sn = dto.getAsString("attc_sn");
		Dto fileDto = (BaseDto) g4Reader.queryForObject("fjglDemo.queryFileBySN", attc_sn);
		String attc_path = fileDto.getAsString("attc_path");
		String title=attc_path.substring(attc_path.lastIndexOf('\\')+1,attc_path.length());
		String filename = G4Utils.encodeChineseDownloadFileName(request, title);
		response.setHeader("Content-Disposition", "attachment; filename=" + filename + ";");
		String path = fileDto.getAsString("attc_path");
		System.out.println(filename);
		System.out.println(path);
		File file = new File(path);
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));  
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);  
        byte[] temp = new byte[1024];  
        int size = 0;  
        while ((size = in.read(temp)) != -1) {  
            out.write(temp, 0, size);  
        }  
        in.close();
		ServletOutputStream os = response.getOutputStream();
		os.write(out.toByteArray());
		os.flush();
		os.close();
		return mapping.findForward(null);
	}
}
	

	
	
	
	
	
	
	
	
	
	
	

	

	

